from django import forms
from django.shortcuts import render, redirect
from django.core.exceptions import ValidationError

from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.encrypt import md5
from app01.utils.bootstrap import BootStrapModelForm


def admin_list(request):
    """管理员列表"""

    # 搜索
    data_dict = {}
    search_data = request.GET.get('q', '')
    if search_data:
        data_dict["user_name__contains"] = search_data

    # 根据搜索条件在数据库中filter
    queryset = models.Admin.objects.filter(**data_dict)

    page_obj = Pagination(request, queryset)

    context = {
        'queryset': page_obj.page_queryset,
        'page_str': page_obj.html(),
        'search_data': search_data
    }
    return render(request, 'admin_list.html', context)


class AdminModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput
    )

    class Meta:
        model = models.Admin
        fields = ['user_name', 'password', 'confirm_password']
        widgets = {
            # render_value=True, 不置空
            'password': forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        # 加密
        return md5(pwd)

    def clean_confirm_password(self):
        confirm = md5(self.cleaned_data.get('confirm_password'))
        pwd = self.cleaned_data.get('password')
        if pwd != confirm:
            raise ValidationError('密码不一致, 请重新输入')
        # 返回什么, 此字段以后保存的数据库就是什么
        return confirm


def admin_add(request):
    """添加管理员"""
    title = '新建管理员'
    if request.method == 'GET':
        form = AdminModelForm()
        return render(request, 'change.html', {'title': title, 'form': form})

    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'change.html', {'form': form, 'title': title})


class AdminEditModelForm(BootStrapModelForm):
    class Meta:
        model = models.Admin
        fields = ['user_name', ]


def admin_edit(request, nid):
    """编辑管理员"""
    # 对象/None
    row_obj = models.Admin.objects.filter(id=nid).first()
    if not row_obj:
        return render(request, 'error.html', {'msg': '数据不存在'})
        # return redirect('/admin/list/')
    title = '编辑管理员'

    if request.method == 'GET':
        form = AdminEditModelForm(instance=row_obj)
        return render(request, 'change.html', {'form': form, 'title': title})

    form = AdminEditModelForm(instance=row_obj, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'change.html', {'form': form, 'title': title})


def admin_delete(request, nid):
    """删除管理员"""

    models.Admin.objects.filter(id=nid).delete()

    return redirect('/admin/list/')


class AdminResetModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput
    )

    class Meta:
        model = models.Admin
        fields = ['password', 'confirm_password']
        widgets = {
            'password': forms.PasswordInput(render_value=False)
        }

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        md5_pwd = md5(pwd)
        # 在数据库中校验 当前密码和新密码是否一致
        exists = models.Admin.objects.filter(id=self.instance.pk, password=md5_pwd).exists()
        if exists:
            raise ValidationError('新密码与旧密码相同')
        # 加密
        return md5_pwd

    def clean_confirm_password(self):
        confirm = md5(self.cleaned_data.get('confirm_password'))
        pwd = self.cleaned_data.get('password')
        if pwd != confirm:
            raise ValidationError('密码不一致, 请重新输入')
        # 返回什么, 此字段以后保存的数据库就是什么
        return confirm


def admin_reset(request, nid):
    """重置密码"""
    row_obj = models.Admin.objects.filter(id=nid).first()
    if not row_obj:
        return redirect('/admin/list/')

    title = f'重置密码 - {row_obj.user_name}'

    if request.method == 'GET':
        form = AdminResetModelForm()
        return render(request, 'change.html', {'form': form, 'title': title})
    form = AdminResetModelForm(data=request.POST, instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'change.html', {'form': form, 'title': title})
